package com.video.internationalvideodisplayproject.pojo.vo;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.video.internationalvideodisplayproject.pojo.BlVideoShootReqDt;
import com.video.internationalvideodisplayproject.pojo.BlVideoShootReqHd;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.sql.Date;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class VideoVO {
    private String billId;
    private String title;
    private String description;
    private String category;
    private String type;
    private String themeId;
    private String duration;
    private String views;
    private List<String> videoUrls;
    private String keywords;
    private String topicName;
    private String videoName;
    private List<ProductList> productLists;
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private Date billDate;

    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private Date deliveryDate; // 完成交付日期

    // 视频文件扩展名常量
    private static final Set<String> VIDEO_EXTENSIONS = Collections.unmodifiableSet(
            new HashSet<>(Arrays.asList(
                    ".mp4", ".avi", ".mov", ".wmv", ".flv", ".webm", ".mkv", ".m4v"
            ))
    );

    private static final String VIDEO_PREFIX_PATH = "https://mms.mumuso.com:8304/internationalVideoDisplayProject/api/file/";

    // 从 BlVideoShootReqHd 实体构造 VideoVO
    public VideoVO(BlVideoShootReqHd entity) {
        // 设置基本信息
        this.billId = entity.getBillId();
        this.title = entity.getVideoName();
        this.videoName = entity.getVideoName(); // 明确设置 videoName
        this.description = entity.getOutDisplayTxt();
        this.category = entity.getCategory();
        this.keywords = entity.getKeywords();
        this.topicName = entity.getTopicName();

        // 处理视频URL，检查是否为视频文件
        this.videoUrls = new ArrayList<>();
        if (isValidVideoUrl(entity.getVideoUrl())) {
            this.videoUrls.add(VIDEO_PREFIX_PATH + entity.getVideoUrl());
        }
        if (isValidVideoUrl(entity.getVideoUrl2())) {
            this.videoUrls.add(VIDEO_PREFIX_PATH + entity.getVideoUrl2());
        }

        // 根据SHOOT_CATEGORY设置type和themeId
        this.type = mapShootCategoryToType(entity.getShootCategory());
        this.themeId = mapShootCategoryToThemeId(entity.getShootCategory(), entity.getTopicName());


        // 设置默认值
        this.duration = "0:00"; // 需要从视频文件获取实际时长
        this.views = generateRandomViews(); // 随机生成观看次数
        this.deliveryDate = entity.getBillDate();
        // 初始化商品列表为空
        this.productLists = new ArrayList<>();
    }

    // 新增：包含商品信息的构造函数
    public VideoVO(BlVideoShootReqHd entity, List<BlVideoShootReqDt> productDetails) {
        this(entity); // 调用原有构造函数

        // 设置商品信息
        if (productDetails != null && !productDetails.isEmpty()) {
            this.productLists = new ArrayList<>();
            for (BlVideoShootReqDt detail : productDetails) {
                ProductList product = new ProductList();
                product.setItemId(detail.getItemId());
                product.setItemName(detail.getItemName());
                // 注意：条码需要从关联表获取，这里暂时设为空
                product.setBarcode(detail.getBarcode()); // 需要通过关联查询获取
                this.productLists.add(product);
            }
        }
    }

    /**
     * 检查视频URL是否有效
     */
    private boolean isValidVideoUrl(String videoUrl) {
        return videoUrl != null &&
               !videoUrl.trim().isEmpty() &&
               isVideoFile(videoUrl);
    }

    /**
     * 检查文件是否为视频文件
     */
    private boolean isVideoFile(String filePath) {
        if (filePath == null || filePath.trim().isEmpty()) {
            return false;
        }
        String lowerPath = filePath.toLowerCase();
        return VIDEO_EXTENSIONS.stream().anyMatch(lowerPath::endsWith);
    }

    /**
     * 生成随机观看次数
     */
    private String generateRandomViews() {
        int views = (int) (Math.random() * 200) + 50;
        return views + "K";
    }

    /**
     * 映射拍摄类别到类型
     */
    private String mapShootCategoryToType(String shootCategory) {
        if (shootCategory == null) return "all";

        switch (shootCategory) {
            case "001":
                return "category"; // 品类视频
            case "002":
                return "theme";    // 主题视频
            default:
                return "all";
        }
    }

    /**
     * 映射拍摄类别和主题名称到主题ID
     */
    private String mapShootCategoryToThemeId(String shootCategory, String topicName) {
        // 只有主题视频（002）才有 themeId
        if (!"002".equals(shootCategory) || topicName == null) {
            return null;
        }

        // 根据主题名称映射themeId
        switch (topicName) {
            case "品牌故事":
                return "brand-story";
            case "企业文化":
                return "corporate-culture";
            case "创新技术":
                return "innovation";
            case "可持续发展":
                return "sustainability";
            case "全球布局":
                return "global-expansion";
            default:
                return "other-theme"; // 未知主题的默认值
        }
    }

    /**
     * 根据category映射具体的type（已废弃，建议使用type字段）
     *
     * @deprecated 使用 getType() 方法替代
     */
    @Deprecated
    public String getCategoryType() {
        if ("002".equals(this.category)) return "theme";
        return "category";
    }

    /**
     * 检查视频是否有有效的视频文件
     */
    public boolean hasValidVideos() {
        return videoUrls != null && !videoUrls.isEmpty();
    }

    /**
     * 获取第一个视频URL
     */
    public String getPrimaryVideoUrl() {
        return (videoUrls != null && !videoUrls.isEmpty()) ? videoUrls.get(0) : null;
    }

}